package cn.itcast.wanxinp2p.account.service;


import cn.itcast.wanxinp2p.common.domain.BusinessException;
import cn.itcast.wanxinp2p.common.domain.CommonErrorCode;
import cn.itcast.wanxinp2p.common.domain.RestResponse;
import cn.itcast.wanxinp2p.common.util.OkHttpUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/*
* 短信服务调用处理类
*
* */
@Service
public class SmsService {

    @Value("${sms.url}")
    private String smsURL;
    @Value("${sms.enable}")
    private Boolean enable;


    /**
     * 校验验证码
     * @param key 校验标识  redis中的键
     * @param code 短信验证码
     */
    public void verifySmsCode(String key, String code) {

        //http://localhost:56085/sailing / verify?name=sms & verificationKey=xxx & verificationCode=xxx


        if (enable){
            StringBuilder url = new StringBuilder(smsURL);
            url.append("verify?name=sms")
                    .append("&verificationKey=")
                    .append(key)
                    .append("&verificationCode=")
                    .append(code);

            RestResponse restResponse = OkHttpUtil.post(url.toString(), "");
            if (restResponse.getCode()!= CommonErrorCode.SUCCESS.getCode()
                    || restResponse.getResult().toString().equalsIgnoreCase("false")){
                //自定义异常
                throw new BusinessException(CommonErrorCode.E_100102);
            }
        }

    }

    //调用短信服务  okHttpUtils
    public RestResponse getSmsMessageCode(String mobile){

        //enable : true 发送验证码到手机  false 测试开发环境  不发验证码
        if (enable){
            StringBuilder url = new StringBuilder(smsURL);
            url.append("generate?effectiveTime=300&name=sms");

            //手机号json参数
            Map<String,String> paramMap = new HashMap<>(1);
            paramMap.put("mobile",mobile);
            //map集合转为json字符串
            String paramJson = JSON.toJSONString(paramMap);

            RestResponse restResponse = OkHttpUtil.post(url.toString(), paramJson);

            return restResponse;
        }else {
            return RestResponse.success();
        }


    }



}
